package com.sunck.modules.system.service;

import com.sunck.common.config.Global;
import com.sunck.common.utils.RedisUtils;
import com.sunck.modules.system.entity.User;
import com.sunck.modules.system.mapper.UserMapper;
import com.sunck.modules.system.utils.UserUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 登录核心逻辑
 *
 * @author LengChen
 * @version 1.0
 * @date 2020/8/4
 */

@Service
public class LoginService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtils redisUtils;

    @Value("${shiro.filterManager.passwordErrNum}")
    private Integer passwordErrNum;


    /**
     * 验证码计数器
     * @param loginCode  用户登录名
     * @param isFail 是否计数+1
     * @param clean 是否清空计数器
     * @return
     */
    public boolean isValidateCodeLogin(String loginCode, boolean isFail, boolean clean) {
        Integer loginFailNum = (Integer) redisUtils.getHashValue(Global.DEFAULT_Code_PARAM,loginCode);
        if (loginFailNum == null){
            loginFailNum = 0;
        }
        if (isFail){
            loginFailNum++;
            redisUtils.setHash(Global.DEFAULT_Code_PARAM,loginCode, loginFailNum);
            User user = UserUtils.getByLoginCode(loginCode);
            if(user!=null && loginFailNum >= passwordErrNum){
                //失败次数过多,账号锁定
                    user.setStatus("2");//停用账号
                    //userMapper.update(user);
            }
        }
        if (clean){
            redisUtils.removeHashKey(Global.DEFAULT_Code_PARAM,loginCode);
        }
        return loginFailNum > 3;//登录失败超过3次显示验证码
    }


    public User getUserByLoginCode(String loginCode) {
        return userMapper.getUserByLoginCode(loginCode);
    }
}
